package com.oa.lms.apps.dao.user.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.lms.apps.dao.user.IPostInfoDao;
import com.oa.lms.apps.entity.user.PostInfoValue;

public class PostInfoDaoImpl extends HibernateDaoSupport implements
		IPostInfoDao {

	List<PostInfoValue> list;
	
	@Override
	public Integer add(PostInfoValue postInfoValue) {
		if (postInfoValue != null) {
			this.getHibernateTemplate().save(postInfoValue);
		}
		return postInfoValue.getPostId();
	}

	@Override
	public void modify(PostInfoValue postInfoValue) {
		if (postInfoValue != null) {
			this.getHibernateTemplate().update(postInfoValue);
		}

	}

	@Override
	public PostInfoValue queryByPostId(Integer postId) {
		if (postId != null) {
			return (PostInfoValue) this.getHibernateTemplate().get(PostInfoValue.class, postId);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PostInfoValue> queryPostInfo(final PostInfoValue postInfoValue) {
		String hqlStr = "FROM PostInfoValue pv WHERE 1=1";
		if (postInfoValue.getPostName() != null) {
			hqlStr += " AND pv.postName = ?";
		}
		if (postInfoValue.getSectionInfo() != null) {
			hqlStr += " AND pv.sectionInfo = ?";
		}
		if (postInfoValue.getStatus() != null) {
			hqlStr += " AND pv.status = ?";
		}
		hqlStr += " AND pv.status <> -1";
		final String hql = hqlStr;
		list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				int index = -1;
				if (postInfoValue.getPostName() != null) {
					query.setString(++index, postInfoValue.getPostName());
				}
				if (postInfoValue.getSectionInfo() != null) {
					query.setEntity(++index, postInfoValue.getSectionInfo());
				}
				if (postInfoValue.getStatus()!= null) {
					query.setInteger(++index, postInfoValue.getStatus());
				}
				list = query.list();
				return list;
			}
		});
		return list;
	}

	public List<PostInfoValue> getList() {
		return list;
	}

	public void setList(List<PostInfoValue> list) {
		this.list = list;
	}

}
